package sale

import (
	"dhfshop/models/sale"
	"dhfshop/utils/helper"
	"time"
	//"strings"
	//"strconv"
	"encoding/json"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

type ProductController struct {
	base.BaseController
}

func (this *ProductController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := sale.GetAllFenxiaoProducts(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	} else {
		r := struct {
		    TotalCount  int64                    `json:"total_count"`
	        Products    []*sale.FenxiaoProduct `json:"products"`
	    }{TotalCount: cnt, Products: l}
	    this.Data["json"] = r
	}
	this.ServeJSON()
}

func (this *ProductController) Download() {
	
}


func (this *ProductController) Post() {
	companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := this.Ctx.Input.GetData("curUserId").(int)
	var v sale.FenxiaoProduct
	valid := validation.Validation{}
	this.ParseForm(&v)
	//valid.Required(v.PartnerId, "partner_id")
	//valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	v.CompanyId = int64(companyId)
	shopId, err := sale.AddFenxiaoProduct(&v)
	if err != nil {
        this.ServeError(err.Error())
		return
    }
	if len(v.SkuJson) > 5 {
	    err := json.Unmarshal([]byte(v.SkuJson), &v)
	    if err != nil {
	        this.ServeError(err.Error())
            return
	    }
	    for _, sku := range v.Skus {
		    sku.CompanyId = v.CompanyId
		    sku.Pid = &v               // pay more attention
	    }
	    if err := sale.AddMultiFenxiaoSkus(v.Skus); err != nil {
		    this.ServeError(err.Error())
            return
	    }
	}
	rsp := struct {
		ShopId    int64        `json:"shop_id"`
	    Created   time.Time    `json:"created"`
	}{ShopId: shopId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ProductController) Put() {
	v := sale.FenxiaoProduct{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	excludeArr := []string{"skus"}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := sale.UpdateFenxiaoProductById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	if len(v.SkuJson) > 0 {
	    arrJson, err := helper.SplitJsonArr(v.SkuJson)
		if err != nil {
			this.ServeError(err.Error())
		    return
		}
	    for _, str := range arrJson {
			var reqSku sale.FenxiaoSku
			if err = json.Unmarshal([]byte(str), &reqSku); err != nil {
				this.ServeError(err.Error())
		        return
			}
			reqSku.Pid = &v               // pay more attention
	   	    if _, err := sale.GetFenxiaoSkuBySkuId(reqSku.Id); err == nil{
				updateField, err := this.GetUpdateFields(reqSku, str, "json", []string{""})
				if err != nil {
					this.ServeError(err.Error())
					return
				}
			    if err := sale.UpdateFenxiaoSkuBySkuId(&reqSku, updateField...); err != nil {
		            this.ServeError(err.Error())
                    return 			
	            }
			}
	    }
	}
	rsp := struct {
		    Pid     int64       `json:"pid"`
	        Modified   time.Time   `json:"modified"`
	    }{Pid:v.Pid, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ProductController) Delete() {
	pid, _ := this.GetInt("pid")
	if err := sale.DeleteFenxiaoProductById(int64(pid)); err == nil {
		rsp := struct {
		    Pid     int       `json:"pid"`
	        Modified   time.Time   `json:"modified"`
	    }{Pid:pid, Modified:time.Now().UTC()}
	    this.Data["json"] = rsp
	} else {
	    this.ServeError(err.Error())
	    return
	}
	this.ServeJSON()
}

func (this *ProductController) StatusShow() {
    companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := sale.FenxiaoProduct{}
	this.ParseForm(&v)
	v.CompanyId = companyId
	valid := validation.Validation{}
	valid.Required(v.Pid, "pid")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.StatusId = 1
    if err := sale.UpdateFenxiaoProductById(&v, "status_id"); err == nil {
	   r := struct {
	        Pid       int64       `json:"pid"`
	        Modified  time.Time   `json:"modified"`
	    }{Pid:v.Pid, Modified:time.Now().UTC()}
	    this.Data["json"] = r
	} else {
	   this.ServeError(err.Error())
	   return
	}
	this.ServeJSON() 
}

func (this *ProductController) StatusUnShow() {
    companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := sale.FenxiaoProduct{}
	this.ParseForm(&v)
	v.CompanyId = companyId
	valid := validation.Validation{}
	valid.Required(v.Pid, "pid")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.StatusId = 0
    if err := sale.UpdateFenxiaoProductById(&v, "status_id"); err == nil {
	   r := struct {
	        Pid       int64       `json:"pid"`
	        Modified  time.Time   `json:"modified"`
	    }{Pid:v.Pid, Modified:time.Now().UTC()}
	    this.Data["json"] = r
	} else {
	    this.ServeError(err.Error())
	    return
	}
	this.ServeJSON() 
}


